import axios from 'axios'
import { useUserStore } from '@stores'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const instance = axios.create({
    //baseURL: 'http://big-event-vue-api-t.itheima.net',
    baseURL:'/api',
    timeout: 10000 // 10秒超时
})
// 请求拦截器
instance.interceptors.request.use(config => {
    const userStore = useUserStore()
    if(userStore.token) config.headers.Authorization = userStore.token
    return config
},err => Promise.reject(err))
// 响应拦截器
instance.interceptors.response.use(res => {
    if(res.data.code === 0) return res.data
    ElMessage.error(res.data.message || '请求失败，请稍后再试！')
    return Promise.reject(res.data)
},err => {
    const router = useRouter()
    if(err.response?.status === 401){
        router.push('/login')
    }

    ElMessage.error(err.response.data.message || '网络异常，请稍后再试！')
    Promise.reject(err)
})


export default instance